/*
 * Copyright (c) 2010 Peter Hayes
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.envconfig.model;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.servlet.ServletException;
import org.hibernate.envers.Audited;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

/**
 *
 * @author Pete
 */
@Entity
@Table(name="CONFIG_GROUP")
@Audited
public class Group {
    @Transient
    private final Logger logger = Logger.getLogger(getClass().getName());

    @Transient
    private EntityManager em;
    
    @Id
    @GeneratedValue
    private int id;

    private String name;

    private String description;

    @ManyToOne
    private Environment environment;
    
    @OneToMany(mappedBy = "group", cascade=CascadeType.ALL)
    private List<Application> applications = new ArrayList<Application>();

    @OneToMany(mappedBy = "group", cascade=CascadeType.ALL)
    private List<Category> categories = new ArrayList<Category>();

    @OneToMany(mappedBy = "group", cascade=CascadeType.ALL)
    private List<ConfigurationKey> keys = new ArrayList<ConfigurationKey>();

    @OneToMany(mappedBy="group", cascade=CascadeType.ALL)
    private List<GroupPermission> permissions = new ArrayList<GroupPermission>();

    public Group(EntityManager em, Environment environment, String name, String description) {
        this.em = em;
        this.environment = environment;
        this.name = name;
        this.description = description;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public void doDelete(StaplerRequest req, StaplerResponse res) throws ServletException, IOException {
        em.remove(this);

        res.sendRedirect2("../..");
    }

    public Application getApplication(String appName) {
        return em.createQuery(
                "SELECT a FROM Application a WHERE a.id = :id and a.group = :group", Application.class)
                .setParameter("name", appName).setParameter("group", this).getSingleResult();
    }

    public void doCreateApplication(StaplerRequest req, StaplerResponse res) throws ServletException, IOException {
        String appName = req.getParameter("name");
        String appDescription = req.getParameter("description");

        // make sure there is no existing app with same name
        List applications = em.createQuery(
                "SELECT a FROM Application a WHERE a.name = :name")
                .setParameter("name", appName).getResultList();

        if (!applications.isEmpty()) {
            // sorry, can't create group with same name
        } else {
            Application application = createApplication(appName, appDescription);
            em.persist(application);
            em.flush();
            res.sendRedirect2("application/" + application.getId());
        }
    }

    public Application createApplication(String appName, String appDescription) {
        Application application = new Application(this, appName, appDescription);
        applications.add(application);
        return application;
    }

    public Category getCategory(String categoryName) {
        return em.createQuery(
                "SELECT c FROM Category a WHERE c.id = :id and c.group = :group", Category.class)
                .setParameter("name", categoryName).setParameter("group", this).getSingleResult();
    }

    public void doCreateCategory(StaplerRequest req, StaplerResponse res) throws ServletException, IOException {
        String categoryName = req.getParameter("name");
        String categoryDescription = req.getParameter("description");

        // make sure there is no existing app with same name
        List categories = em.createQuery(
                "SELECT c FROM Category a WHERE c.name = :name")
                .setParameter("name", categoryName).getResultList();

        if (!categories.isEmpty()) {
            // sorry, can't create group with same name
        } else {
            Category category = createCategory(categoryName, categoryDescription);
            em.persist(category);
            em.flush();
            res.sendRedirect2("category/" + category.getId());
        }
    }

    public Category createCategory(String categoryName, String categoryDescription) {
        Category category = new Category(this, categoryName, categoryDescription);
        categories.add(category);
        return category;
    }

    public ConfigurationKey createConfigurationKey(String keyName, String keyDescription) {
        ConfigurationKey key = new ConfigurationKey(this, keyName, keyDescription);
        keys.add(key);
        return key;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Group other = (Group) obj;
        if (this.id != other.id) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        return id;
    }
}
